import {createStore} from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import {ElMessage} from 'element-plus'
import router from "@/router";
import {iget, ipost, iput} from "@/api";

export default createStore({
    state: {
        token: null,
        username: null,
        id: null,
        data: {},
        role: null,
        menuRoutes: [],
        users: [],
        recentDeleteUsers: [],
        academicOrigin: {},
        userPageInfo: {
            currentPage: 1,
            pageSize: 10,
            total: 0
        },
        activeTeachers: 0,
        retiredTeachers: 0
    },
    getters: {
        token: state => state.token,
        menuRoutes: state => state.menuRoutes,
        users: state => state.users,
        recentDeleteUsers: state => state.recentDeleteUsers, // 新增getter
        userPageInfo: state => state.userPageInfo
    },
    mutations: {
        logout(state) {
            state.token = null;
            state.data = {};
            state.role = null;
            state.username = null;
            state.menuRoutes = [];
            state.academicOrigin = {};
            ElMessage("已退出登录")
        },
        setUsername(state, username) {
            state.username = username
        },
        removeUsername(state) {
            state.username = null
        },
        setToken(state, token) {
            state.token = token
        },
        removeToken(state) {
            state.token = null
        },
        setData(state, data) {
            state.data = data;
            if (data.name !== undefined) {
                state.username = data.name;
            }
            state.id = data.id;
            if (data.isAdmin !== undefined) {
                state.role = data.isAdmin === 1 ? 'admin' : 'normal';
                state.menuRoutes = router.options.routes.find(r => r.path === '/home').children.filter(route => {
                    if (route.meta?.requiresAdmin) {
                        return state.role === 'admin';
                    }
                    return true;
                });
            }
        },
        setRole(state, role) {
            state.role = role;
            state.menuRoutes = router.options.routes.find(r => r.path === '/home').children.filter(route => {
                if (route.meta?.requiresAdmin) {
                    return state.role === 'admin';
                }
                return true;
            });
        },
        removeRole(state) {
            state.role = null
        },
        setUsers(state, users) {
            state.users = users;
        },
        setUserPageInfo(state, pageInfo) {
            state.userPageInfo = pageInfo;
        },
        setAcademicOrigin(state, academicOrigin) {
            state.academicOrigin = academicOrigin;
        },
        setTeachersCount(state, {active, retired}) {
            state.activeTeachers = active;
            state.retiredTeachers = retired;
        },
        setUsersRecentDelete(state, users) {
            state.recentDeleteUsers = users;
        },
    },
    actions: {
        async updateProfile({commit}, formData) {
            try {
                let res = await iput('/user/updateUser', formData)
                res = res.data
                if (res.code === 200) {
                    ElMessage.success('保存成功')
                    commit('setData', formData)
                } else {
                    ElMessage.error('保存失败，请稍后再试')
                }
            } catch (e) {
                ElMessage.error('保存失败，请稍后再试')
                console.log('保存失败，' + e)
            }
        },
        // eslint-disable-next-line no-unused-vars
        async updateAcademicOrigin({commit}, academicOriginData) {
            try {
                let res = await iput('/academicOrigin/updateAcademicOrigin', academicOriginData)
                res = res.data
                if (res.code === 200) {
                    ElMessage.success('学缘信息更新成功')
                    // commit('setAcademicOrigin', academicOriginData)
                } else {
                    ElMessage.error('学缘信息更新失败，请稍后再试')
                }
            } catch (e) {
                ElMessage.error('学缘信息更新失败，请稍后再试')
                console.log('学缘信息更新失败，' + e)
            }
        },
        async getAcademicOrigin({commit}) {
            try {
                let res = await iget('/academicOrigin/getAcademicOriginById', {id: this.state.id})
                res = res.data
                if (res.code === 200) {
                    commit('setAcademicOrigin', res.result)
                } else {
                    ElMessage.error('获取学缘信息失败，请稍后再试')
                }
            } catch (e) {
                ElMessage.error('获取学缘信息失败，请稍后再试')
                console.log('获取学缘信息失败，' + e)
            }
        },
        async handleLogin({commit}, {username, password}) {
            try {
                let res = await ipost('/auth/login', null, {
                    params: {
                        username,
                        password
                    }
                })
                res = res.data
                if (res.code !== 200) {
                    throw new Error(res.message)
                }
                if (res.result) {
                    commit('setToken', res.result)
                    ElMessage.success('登录成功')
                    await router.push('/home')
                } else {
                    ElMessage.error('登录失败，请检查工号和密码')
                }
            } catch (error) {
                ElMessage.error('登录失败，' + error)
            }
        },
        async getUserinfo({commit}) {
            try {
                const res = await iget('/user/getUserinfo');
                if (res.data.code === 200) {
                    commit('setData', res.data.result);
                } else {
                    throw new Error(res.data.message);
                }
            } catch (error) {
                ElMessage.error('获取用户信息失败: ' + error.message);
            }
        },
        async fetchUsersRecentDelete({commit}, status = 1) {
            try {
                const response = await iget(`/user/getAllUser`, {
                    pageNum: 1,//也可以不带这个参数，后端有默认值
                    pageSize: 25,
                    deleteStatus: status
                });
                commit('setUsersRecentDelete', response.data.result.records);
            } catch (error) {
                ElMessage.error('获取用户数据失败');
                console.error(error);
            }
        },
        async fetchUsers({commit, state}) {
            try {
                const response = await iget(`/user/getAllUser`, {
                    pageNum: state.userPageInfo.currentPage,
                    pageSize: state.userPageInfo.pageSize,
                });
                commit('setUsers', response.data.result.records);
                commit('setUserPageInfo', {
                    currentPage: state.userPageInfo.currentPage,
                    pageSize: state.userPageInfo.pageSize,
                    total: response.data.result.total
                });
            } catch (error) {
                ElMessage.error('获取用户数据失败');
                console.error(error);
            }
        },

    },
    modules: {},
    plugins: [createPersistedState()]
});
